import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_yres/model/car/car_cate_model.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
// import './tb_list_page.dart';
import 'package:cached_network_image/cached_network_image.dart';

class CarCategoryPage extends StatefulWidget {
  CarCategoryPage({Key key}) : super(key: key);

  _CarCategoryPageState createState() => _CarCategoryPageState();
}

class _CarCategoryPageState extends State<CarCategoryPage> {
  int _selectIndex = 0;
  List _leftCateList = [];
  List _rightCateList = [];
    double kScreenWidth = ScreenUtil.getInstance().setWidth(750);
    double kScreenHeight = ScreenUtil.getInstance().setHeight(1334);
    double kMargin5 = ScreenUtil.getInstance().setWidth(5);
    double kMargin10 = ScreenUtil.getInstance().setWidth(10);
    double kMargin8 = ScreenUtil.getInstance().setWidth(8);
    double kMargin15 = ScreenUtil.getInstance().setWidth(15);
    double kMargin20 = ScreenUtil.getInstance().setWidth(20);
    double kMargin25 = ScreenUtil.getInstance().setWidth(25);
    double kMargin28 = ScreenUtil.getInstance().setWidth(28);
    double kMargin100 = ScreenUtil.getInstance().setWidth(100);
    double kMargin120 = ScreenUtil.getInstance().setWidth(120);
    double kSearchBarHeight = ScreenUtil.getInstance().setWidth(60);

  @override
  void initState() {
    super.initState();
    _getLeftCateData();
  }

  //左侧数据：
  _getLeftCateData() async {
    FormData data = new FormData.fromMap({});
    Response<String> response =
        await HttpUtil().post(Api.GetTopCatListUrl, data: data);
    Map userMap = json.decode(response.data);
    CarCateModelEntity itemEntity = new CarCateModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          _leftCateList.clear();
          _leftCateList = itemEntity.data;
          _getRightCateData(_leftCateList[0].cat_id);
        });
      }
    }
  }

  //右侧数据：
  _getRightCateData(pid) async {
    FormData data = new FormData.fromMap({'pid': pid});
    Response<String> response =
        await HttpUtil().post(Api.GetSubListByParentUrl, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    CarCateModelEntity itemEntity = new CarCateModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          _rightCateList.clear();
          _rightCateList = itemEntity.data;
        });
      }
    }
  }

  //左侧组件
  Widget _leftCateWidget(leftWidth) {
    if (this._leftCateList.length > 0) {
      return Container(
        width: leftWidth,
        height: double.infinity,
        // color: Colors.red,
        child: ListView.builder(
          itemCount: this._leftCateList.length,
          itemBuilder: (context, index) {
            return Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    setState(() {
                      // setState(() {
                      _selectIndex = index;
                      this._getRightCateData(this._leftCateList[index].cat_id);
                    });
                    print(_selectIndex);
                  },
                  child: Container(
                    width: double.infinity,
                    height: ScreenUtil.getInstance().setHeight(70),
                    padding: EdgeInsets.all(kMargin20),
                    child: Text("${this._leftCateList[index].name}",
                        textAlign: TextAlign.center),
                    color: _selectIndex == index
                        ? Color.fromRGBO(240, 246, 246, 0.9)
                        : Colors.white,
                  ),
                ),
                Divider(height: 1),
              ],
            );
          },
        ),
      );
    } else {
      return Container(
        width: leftWidth,
        height: double.infinity,
      );
    }
  }

  //右侧组件：
  Widget _rightCateWidget(rightItemWidth, rightItemHeigth) {
    if (this._rightCateList.length > 0) {
      return Expanded(
        flex: 1,
        child: Container(
          padding: EdgeInsets.all(10),
          height: double.infinity,
          color: Color.fromRGBO(240, 246, 246, 0.9),
          // color: Colors.blue,
          child: GridView.builder(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                childAspectRatio: rightItemWidth / rightItemHeigth,
                crossAxisSpacing: kMargin20*4,
                mainAxisSpacing: kMargin20*3),
            itemCount: this._rightCateList.length,
            itemBuilder: (context, index) {
              return Container(
                // padding: EdgeInsets.all(ScreenAdaper.width(20)),
                child:GestureDetector(
                  onTap: (){
                    // print(this._rightCateList[index].taobao_cat_id);
                    // Navigator.of(context)
                    //       .push<String>(MaterialPageRoute(builder: (context) {
                    //     return new TBListPage(search: this._rightCateList[index].name);
                    //   }));
                  },
                  child: Column(
                  children: <Widget>[
                    AspectRatio(
                      aspectRatio: 1 / 1,
                      child: 
                      CachedNetworkImage(
      fit: BoxFit.cover,
      imageUrl: Api.BaseUrl+this._rightCateList[index].icon,
      placeholder: (context, url) => Image.asset(
        'images/pic_default.png',
        fit: BoxFit.fill,
      ),
      errorWidget: (context, url, error) => Image.asset(
        'images/pic_default.png',
        fit: BoxFit.fill,
      ),
    )
                    ),
                    Container(
                      height: ScreenUtil.getInstance().setHeight(32),
                      child: Text("${this._rightCateList[index].name}"),
                    )
                  ],
                )
                ),
              );
            },
          ),
        ),
      );
    } else {
      return Expanded(
          flex: 1,
          child: Container(
            padding: EdgeInsets.all(10),
            height: double.infinity,
            color: Color.fromRGBO(240, 246, 246, 0.9),
            child: Text('加载中...'),
          ));
    }
  }

  Widget build(BuildContext context) {
       ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    //计算右侧GridView宽高比：
    var leftWidth = kScreenWidth / 4;
    //右侧宽高=总宽度-左侧宽度-Gridview外层元素左右的Padding值-GridView中间的间距
    var rightItemWidth = (kScreenWidth - leftWidth - 20 - 20) / 3;
    rightItemWidth = ScreenUtil.getInstance().setWidth(rightItemWidth);
    var rightItemHeigth = rightItemWidth + ScreenUtil.getInstance().setHeight(32);

    return Scaffold(
        appBar: AppBar(
          title: Text('分类'),
        ),
        body: Row(
          children: <Widget>[
            _leftCateWidget(leftWidth),
            _rightCateWidget(rightItemWidth, rightItemHeigth)
          ],
        ));
  }
}
